package mi.payment.utils;

import android.annotation.SuppressLint;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;

import mi.payment.MyApplication;

/**
 * <pre>
 * Toast管理类
 * 20170913重构，重构点如下：
 * （1）删除所有静态变量，改为单例模式
 * （2）所有弹出Toast操作都在UI线程执行，业务代码可以直接调用showToast接口，无需考虑线程安全性
 * （3）保留原MToast连续相同的消息不重复显示机制
 * </pre>
 */
public final class MToast {

    private static MToast instance;
    private Toast toast;
    private String curMsg;
    private int duration;
    private boolean isShowing;

    @SuppressLint("ShowToast")
    private MToast() {
        toast = Toast.makeText(MyApplication.app, null, Toast.LENGTH_SHORT);
    }

    public static void showToast(int resId) {
        showToast(resId, Toast.LENGTH_SHORT);
    }

    public static void showToast(int resId, int duration) {
        showToast(MyApplication.app.getString(resId), duration);
    }

    public static void showToast(String msg) {
        showToast(msg, Toast.LENGTH_SHORT);
    }

    public static void showToast(final String msg, final int duration) {
        if (Looper.myLooper() != Looper.getMainLooper()) {//非UI线程
            MyApplication.app.post(new Runnable() {
                @Override
                public void run() {
                    showToastOnUIThread(msg, duration);
                }
            });
        } else {//UI线程
            showToastOnUIThread(msg, duration);
        }
    }

    private static void showToastOnUIThread(String msg, int duration) {
        if (instance == null) {
            instance = new MToast();
        }
        instance.toast.setDuration(duration);
        instance.duration = 2000;//短toast
        if (duration == Toast.LENGTH_LONG || duration >= 3500) {
            instance.duration = 3500;//长toast
        }
        if (!instance.isShowing || TextUtils.isEmpty(msg)
                || !TextUtils.equals(msg, instance.curMsg)) {
            instance.toast.setText(msg);
            instance.toast.show();
            instance.curMsg = msg;
            instance.isShowing = true;
            MyApplication.app.getMainHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    instance.toast.cancel();
                    instance.isShowing = false;
                    instance.curMsg = null;
                    instance.duration = 0;
                }
            }, instance.duration);
        }
    }

    public static void cancel() {
        if (instance != null) {
            instance.toast.cancel();
        }
    }

}
